var toast = require("../../../components/toast/toast.js")
var app = getApp();
var currentPage;
var needLoadingTotal = 0;
var needInputIsShow = 0;
var changePhoneAutoSaving = false;
var ChangeSubscribeViolationAutoSaving = false;
Page({
  data: {
    // text:"这是一个页面"
    //主键
    carId: 0,
    //车牌前缀
    carNumberPrefix: "粤",
    //车牌后缀
    carNumberSuffix: "",
    //车牌
    carNumber: "",
    //车牌用于显示
    readOnlyCarNumber: "",
    //车架
    carCode: "",
    readOnlyCarCode: "",
    //发动机
    carDriver: "",
    readOnlyCarDriver: "",
    //需要添加车架号
    needCarCode: false,
    //车架号长度
    carCodeLength: 0,
    //车架号提示
    carCodeInputplaceholder: "",
    //需要填写发动机号
    needCarDriver: false,
    //发动机号长度
    carDriverLength: 0,
    //发动机号提示
    carDriverInputplaceholder: "",
    //车架、发动机输入配置
    inputConfig: [],
    inputConfigViewModel: [],
    //是否订阅违章通知
    subscribeViolation: true,
    //手机号
    userPhone: "",
    //显示的手机号
    readOnlyUserPhone: "",
    // 显示补充资料按钮
    showupdate: true,

    //需要加载资源总量
    //needLoadingTotal: 0,
    carNumberPrefixListHidden: true,
    //示例图片
    samplePictureHidden: "hide",
    samplePictureSrc: "/image/EngineImgA.png",
    //错误
    errors: [],
    errorClass: "hide",
    toast1Hidden: true,
    //禁用可编辑项
    inputIsDisabled: false,
    carInfoInputIsDisabled: false,
    //删除弹窗
    modalHidden: true
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    this.load(options.id);

    // 填充车辆信息的接口
    if(this.data.carId!=0){this.getExistDataList();}
  },
  onReady: function () {
    // 页面渲染完成
    var carId = this.data.carId;
    if (carId == 0) {
      wx.setNavigationBarTitle({ title: "添加车辆" });
    } else {
      wx.setNavigationBarTitle({ title: "车辆详情" });
    }
  },
  onShow: function () {
    // 页面显示
    var carId = this.data.carId;
    if (carId == 0) {
      wx.setNavigationBarTitle({ title: "添加车辆" });
    } else {
      wx.setNavigationBarTitle({ title: "车辆详情" });
    }
  },
  onHide: function () {
    --needInputIsShow
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  /**加载已经填写过资料 */
  getExistDataList: function (e) {
    var param = {
      api: 'Service.UcCar.CarService.SelectCarRequirements',
	    url: '/wx/carViola/selectCarRequirements.ajax',
	    para: {
        'carId': this.data.carId
      }
    };
    app.requestSdkForNeedLogin({
      param: param,
      beforeSend: () => {
        //发送请求之前执行

      },
      success: data => {
        if (data.successFlag) {
          let list = data.data;
          var listFilter = {},selectCarLen = false;
          for(var listKey in list){
            if(list[listKey]!=''){
                listFilter[listKey] = list[listKey]
            }
            if(list[listKey]!=''){
              selectCarLen = true
            }
          }
         
          if (!selectCarLen) {
            this.setData({
              showupdate: false
            });
          }
        } else {
          toast.show(this, data.errormsg)
        }

      },
      complete: data => {
      }
    });
  },
  load: function (id) {
    var that = this;
    //页面加载
    needLoadingTotal = 2;

    // 添加车辆，才加载
    //加载输入配置  车辆前缀列表
    this.loadInputConfig();

    if (id) {  //查看资料有carId不请求车辆信息
      this.setData({
        carId: id,
        carInfoInputIsDisabled: true
      });
      needLoadingTotal = 3;
      this.loadCar(id,function(){
        // that.carPrefixChange(that.data.carNumberPrefix)
      });
    }else{
      var tiems = setInterval(()=>{
          if(needInputIsShow >= 1){
            clearInterval(tiems)
            this.setData({
              carNumberPrefix: this.data.carNumberPrefix
            })
            this.carPrefixChange(this.data.carNumberPrefix)    
          }
      },250)
    }
  
    //加载车牌前缀
    // this.loadCarNumberPrefix();
    // this.setData({
    //  carNumberPrefix: '粤', //data.data.provinceAlias
    //  needCarCode: true
    // });
    let carId = this.data.carId;
    if (carId != 0) {
   
    }
  },
  loadCar: function (carId,callBack) {
    //加载车辆信息
    var param = {
      api: "Service.UcCar.CarService.SelectCar",
	    url: '/wx/carViola/selectCar.ajax',
	    para: { carId: carId }
    };

    app.requestSdkForNeedLogin({
      param: param,
      beforeSend: () => {
        //发送请求之前执行
        wx.showToast({
          title: '请稍候',
          icon: 'loading',
          duration: 10000
        });
      },
      success: data => {
        if (data.successFlag) {
        this.setData({
            //车牌前缀
            carNumberPrefix: data.data.carNumber.substr(0, 1),
            //车牌后缀
            carNumberSuffix: data.data.carNumber.substr(1, data.data.carNumber.length),
            //车牌
            carNumber: data.data.carNumber,
            //车牌用于显示
            readOnlyCarNumber: data.data.carNumber.substr(1, data.data.carNumber.length),
            //车架
            carCode: data.data.carCode == 'null'&&data.data.carCode == null?'':data.data.carCode,
            readOnlyCarCode: data.data.carCode,
            needCarCode: data.data.carCode!='null'&&data.data.carCode != null?true:false,
            //发动机
            carDriver: data.data.engineNumber,
            readOnlyCarDriver: data.data.engineNumber,
            needCarDriver: data.data.engineNumber!='null'&&data.data.engineNumber!=null?true:false,
            //是否订阅违章通知
            subscribeViolation: data.data.isSubscribe,
            //手机号
            userPhone: data.data.userTelephone != 'null'?data.data.userTelephone:'',
            readOnlyUserPhone: data.data.userTelephone != 'null'?data.data.userTelephone:''
          });

          typeof callBack == 'function'&&callBack()
        } else {
          toast.show(this, data.errormsg)
        }
      },
      complete: data => {
        needLoadingTotal--
        wx.hideToast();
      }
    });
  },
  loadInputConfig: function () {
    //加载输入配置
    var param = {
	    url: '/wx/carViola/getAddCarInfo.ajax'
    };

    app.requestSdkForNeedLogin({
      param: param,
      beforeSend: () => {
        //发送请求之前执行
        // wx.showToast({
        //     title: '请稍候',
        //     icon: 'loading',
        //     duration: 10000,
        //     mask: true
        // });
      },
      success: data => {
        if (data.successFlag) {
          data.data = JSON.parse(data.data);
          this.setData({
            inputConfig: data.data
          });
          var temp = new Array();
          for (var i = 0; i < data.data.length; i++) {
            var province = data.data[i];
            var city = province.Cities[0];
            var item = {
              prefix: province.ProvincePrefix,
              carCodeLen: city.CarCodeLen,
              carEngineLen: city.CarEngineLen,
              provinceName: province.ProvinceName
            };
            temp.push(item);
          }
          this.setData({
            inputConfigViewModel: temp
          });
        } else {
          toast.show(this, data.errormsg)
        }
      },
      complete: data => {
        ++needInputIsShow;

        needLoadingTotal--
        wx.hideToast();
      }
    });
  },
  loadCarNumberPrefix: function () {
    //加载车牌前缀
    if (this.data.carId) {
      needLoadingTotal--
      return;
    }

    wx.getLocation({
      type: 'wgs84',
      success: (res) => {
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy
        var param = {
          api: "Service.UcCar.CarService.GetCityName",
	        url: '/wx/carViola/getCityName.ajax',
          para: { "longitude": longitude, "latitude": latitude }
        };
        app.requestSdkForNeedLogin({
          param: param,
          beforeSend: () => {
            //发送请求之前执行
            // wx.showToast({
            //     title: '请稍候',
            //     icon: 'loading',
            //     duration: 10000,
            //     mask: true
            // });
          },
          success: data => {
            if (data.successFlag) {
              this.setData({
                carNumberPrefix: data.data.provinceAlias
              });
            } else {
              toast.show(this, data.errormsg)
            }
          },
          complete: data => {
            needLoadingTotal--
            wx.hideToast();
          }
        });
      },
      fail: (res) => {
        this.setData({
          carNumberPrefix: "粤"
        });
        needLoadingTotal--
      }
    })
  },
  carPrefixChange: function (carNumber) {
    console.log(carNumber)
    //改变车牌时，判断车架号和发动机号
    if (!carNumber) {
      return;
    }
    var prefix = carNumber.substr(0, 1);
    var prefix2 = carNumber.substr(0, 2);
    var inputConfig = this.data.inputConfig;

    //根据车牌前缀，获取省份
    for (var i = 0; i < inputConfig.length; i++) {
      if (inputConfig[i].ProvincePrefix === prefix) {
        //根据车牌前两位，获取城市
        for (var j = 0; j < inputConfig[i].Cities.length; j++) {
          //直辖市不需要判断第二位
          if (inputConfig[i].Cities[j].CarNumberPrefix === prefix2 || (prefix === prefix2)) {
            //var carCodeLen = 0, carEngineLen = 0;
            var carCodeLen = inputConfig[i].Cities[j].CarCodeLen;
            var carEngineLen = inputConfig[i].Cities[j].CarEngineLen;
            if (carCodeLen > 0) {
              if (carCodeLen === 99) {
                this.setData({
                  carCodeInputplaceholder: "请输入完整车架号"
                });
              } else {
                this.setData({
                  carCodeInputplaceholder: "请输入车身架号后" + carCodeLen + "位"
                });
              }
              this.setData({
                carCodeLength: carCodeLen,
                needCarCode: true
              });
            } else {
              this.setData({
                needCarCode: false
              });
            }

            if (carEngineLen > 0) {
              if (carEngineLen === 99) {
                this.setData({
                  carDriverInputplaceholder: "请输入完整发动机号"
                });
              } else {
                this.setData({
                  carDriverInputplaceholder: "请输入发动机号后" + carEngineLen + "位"
                });
              }
              this.setData({
                carDriverLength: carEngineLen,
                needCarDriver: true
              });
            } else {
              this.setData({
                needCarDriver: false
              });
            }
            break;
          }
        }
        break;
      }
    }

    //if (element) {
    //    $(element).addClass("active").siblings().removeClass("active");
    //} else {

    //}
  },
  selectPrefix: function () {
    //选择车牌前缀
    if (this.data.carId != 0) {

    } else {
      this.setData({
        carNumberPrefixListHidden: false
      });
    }


  },
  cancelSelectPrefix: function () {
    //取消选择车牌前缀
    this.setData({
      carNumberPrefixListHidden: true
    });
  },
  selectPrefixItem: function (e) {
    //选中车牌前缀
    this.setData({
      carNumberPrefix: e.currentTarget.dataset.prefix
    });
    this.carPrefixChange(e.currentTarget.dataset.prefix);
    this.cancelSelectPrefix();
  },
  carNumberInput: function (e) {
    //输入车牌
    var value = e.detail.value;

    var carNumber = this.data.carNumberPrefix + value
    this.setData({
      carNumberSuffix: value,
      carNumber: carNumber
    });

    return value.replace(/[a-z]/g, function (ch) { return String.fromCharCode(ch.charCodeAt(0) & ~32); });



    //return value;
  },
  carNumberBlur: function (e) {
    //车牌号失去焦点  
    var value = e.detail.value;
    value = value.toUpperCase();

    this.setData({
      readOnlyCarNumber: value
    });

    return value;
  },

  carDriverInput: function (e) {
    //输入发动机号

    var value = e.detail.value.trim();
    this.setData({
      carDriver: value
    });
    return value.replace(/[a-z]/g, function (ch) { return String.fromCharCode(ch.charCodeAt(0) & ~32); });

    //return value;

  },
  carDriverBlur: function (e) {
    //发动机号失去焦点
    var value = e.detail.value;
    value = value.toUpperCase();

    this.setData({
      readOnlyCarDriver: value
    });

    return value;
  },
  carCodeInput: function (e) {
    //输入车架号  
    var value = e.detail.value.trim();

    this.setData({
      carCode: value
    });
    return value.replace(/[a-z]/g, function (ch) { return String.fromCharCode(ch.charCodeAt(0) & ~32); });
    //return value;
  },
  carCodeBlur: function (e) {
    //车架号失去焦点
    var value = e.detail.value;
    value = value.toUpperCase();

    this.setData({
      readOnlyCarCode: value
    });

    return value;
  },

  //手机号码change
  userPhoneInput: function (e) {
    //输入手机号
    var value = e.detail.value.trim();

    //value = value.toUpperCase();
    setTimeout(() => {
      this.setData({
        userPhone: value
      });

      if (value.length == 11) {

        //如果是编辑的话，直接保存
        if (this.data.carId != 0 && changePhoneAutoSaving == false) {
          changePhoneAutoSaving = true;
          ChangeSubscribeViolationAutoSaving = false;
          this.submit();
        } else {
          this.verifyUserPhone();
        }
      }
    }, 500);
    //return value;
  },

  // auto-fill 快充后取值
  carNumberChange: function (e) {
    //车牌号 改变
    this.setData({
      carNumberSuffix: e.detail.value,
      readOnlyCarNumber: e.detail.value
    });

  },
  carDriverChange: function (e) {
    //发动机号 改变
    this.setData({
      carDriver: e.detail.value,
      readOnlyCarDriver: e.detail.value
    });

  },
  carCodeChange: function (e) {
    //车身架号 改变
    this.setData({
      carCode: e.detail.value,
      readOnlyCarCode: e.detail.value
    });

  },
  userPhoneChange: function (e) {
    //手机号码 改变
    this.setData({
      userPhone: e.detail.value,
      readOnlyUserPhone: e.detail.value
    });

    var value = e.detail.value;
    setTimeout(() => {
      if (value.length == 11) {

        //如果是编辑的话，直接保存
        if (this.data.carId != 0 && changePhoneAutoSaving == false) {
          changePhoneAutoSaving = true;
          ChangeSubscribeViolationAutoSaving = false;
          this.submit();
        } else {
          this.verifyUserPhone();
        }
      }
    }, 500);

  },
  // auto-fill 快充后取值-end

  subscribeViolationChange: function (e) {
    //订阅
    this.setData({
      subscribeViolation: e.detail.value
    });

    if (this.data.carId != 0) {
      ChangeSubscribeViolationAutoSaving = true;
      this.setData({
        inputIsDisabled: ChangeSubscribeViolationAutoSaving
      });

      if(!this.data.subscribeViolation){
        this.setData({
	        "readOnlyUserPhone":''
        })
      }
      console.log(typeof this.data.carDriver)
      //创建或更新
      var param = {
        "userId": "",
        "carType": "02",
        "carId": this.data.carId,
        "carNumber": this.data.carNumber,
        "carCode": this.data.carCode == 'null'?'null':this.data.carCode,
        "engineNumber": this.data.carDriver == 'null'?'null':this.data.carDriver,
        "remark": "",
        "isSubscribe": this.data.subscribeViolation ? "1" : "0",
        "phone": this.data.subscribeViolation?this.data.userPhone:'',
        //"userType": "app",
        //"userName": "testuser",
        "annualCheckTime": "",
        "annualCheckFlag": "",
        "registryNo": "",
        "carModelId": "",
        "appName": ""
      };
      this.update(param);
    }
  },
  iconTap: function (e) {
    //车架号发动机号图片
    var type = e.currentTarget.dataset.type;
    if (type == "carCode") {
      this.setData({
        samplePictureHidden: "",
        samplePictureSrc: "/image/EngineImgA.png"
      });
    } else {
      this.setData({
        samplePictureHidden: "",
        samplePictureSrc: "/image/EngineImgB.png"
      });
    }
  },
  samplePictureTap: function () {
    //点击示例图片背景
    this.setData({
      samplePictureHidden: "hide",
    });
  },
  verifyCarNumber: function () {
    //验证车牌
    let last_carNumberSuffix = this.data.carNumberSuffix;


    if (last_carNumberSuffix.trim() == "") {
      this.setData({
        "errors[0]": "请输入车牌号码",
        errorClass: "",
        readOnlyCarNumber: last_carNumberSuffix
      });

    } else if (!/^[A-Z_a-z]{1}[A-Z_a-z_0-9]{5,6}$/.test(last_carNumberSuffix.trim())) {
      this.setData({
        "errors[0]": "请输入正确的车牌",
        errorClass: "",
        readOnlyCarNumber: last_carNumberSuffix
      });
    } else {
      var carNumber = this.data.carNumberPrefix + last_carNumberSuffix
      this.setData({
        errors: [],
        errorClass: "hide",
        carNumber: carNumber,
        readOnlyCarNumber: last_carNumberSuffix
      });
    }
  },
  verifyUserPhone: function () {
    //验证手机号
    if (!this.data.subscribeViolation) {
      this.setData({
        errors: [],
        errorClass: "hide",
      });
      return;
    }

    if (this.data.userPhone.trim() == "") {
      this.setData({
        "errors[0]": "请输入手机号",
        errorClass: "",
      });
    } else if (!/^[1]{1}[3|4|5|7|8]{1}[0-9]{9}$/.test(this.data.userPhone.trim())) {
      this.setData({
        "errors[0]": "请输入正确的手机号",
        errorClass: "",
      });
    } else {
      this.setData({
        errors: [],
        errorClass: "hide",
      });
    }
  },
  submit: function (e) {
    //新增或编辑
    this.verifyCarNumber();

    if (this.data.errors.length > 0) {
      this.setData({
        errorClass: ""
      });
      return;
    }

    //如果需要发动机号
    if (this.data.needCarDriver && this.data.carDriver.trim() === "") {
      this.setData({
        "errors[0]": "请输入发动机号",
        errorClass: ""
      });
      return;
    } else if (this.data.needCarDriver && this.data.carDriverLength !== 99 && this.data.carDriverLength > this.data.carDriver.trim().length) {
      this.setData({
        "errors[0]": this.data.carDriverInputplaceholder,
        errorClass: ""
      });
      return;
    } else if (!this.data.needCarDriver) {
      this.setData({
        carDriver: "",
      });
    }

    //如果需要车架号
    if (this.data.needCarCode && this.data.carCode.trim() === "") {
      this.setData({
        "errors[0]": "请输入车架号",
        errorClass: ""
      });
      return;
    } else if (this.data.needCarCode && this.data.carCodeLength !== 99 && this.data.carCodeLength > this.data.carCode.trim().length) {
      this.setData({
        "errors[0]": this.data.carCodeInputplaceholder,
        errorClass: ""
      });
      return;
    } else if (!this.data.needCarCode) {
      this.setData({
        carCode: "",
      });
    }

    //不验证手机号
    if (!ChangeSubscribeViolationAutoSaving) {
      //手机号
      this.verifyUserPhone();
      if (this.data.errors.length > 0) {
        this.setData({
          errorClass: ""
        });
        changePhoneAutoSaving = false;
        return;
      }
    }

// 加个loading效果 
    wx.showToast({
      title: '请稍候',
      icon: 'loading',
      duration: 10000
    });
    
    //创建或更新
    var param = {
      "userId": "",
      "carType": "02",
      "carId": this.data.carId,
      "carNumber": this.data.carNumber,
      "carCode": this.data.carCode,
      "engineNumber": this.data.carDriver == 'null'?'':this.data.carDriver,
      "remark": "",
      "isSubscribe": this.data.subscribeViolation ? "1" : "0",
      "phone": this.data.userPhone,
      //"userType": "app",
      //"userName": "testuser",
      "annualCheckTime": "",
      "annualCheckFlag": "",
      "registryNo": "",
      "carModelId": "",
      "appName": ""
    };

    if (this.data.carId != 0) {
      this.update(param);
    } else {
      this.create(param);
    }



  },
  create: function (param) {
    //新增
    var temp = param;
    var param = {
      api: "Service.UcCar.CarService.InsertCar",
	    url: '/wx/carViola/insertCar.ajax',
      para: temp
    };
    app.requestSdkForNeedLogin({
      param: param,
      beforeSend: () => {
        //发送请求之前执行
        // wx.showToast({
        //     title: '请稍候',
        //     icon: 'loading',
        //     duration: 10000
        // });
      },
      success: data => {
        if (data.successFlag) {
          this.setData({
            toast1Hidden: false
          });

          setTimeout(() => {
            wx.navigateBack({
              delta: 1
            })
          }, 1000);
        } else {
          this.setData({
            "errors[0]": data.errormsg,
            errorClass: ""
          });
          setTimeout(() => {
            this.setData({
              errors: [],
              errorClass: "hide",
            });
          }, 1500);
        }
      },
      complete: data => {
        wx.hideToast();
      }
    });
  },
  update: function (param) {
    //编辑
    var temp = param;
    var param = {
      api: "Service.UcCar.CarService.UpdateCar",
	    url: '/wx/carViola/updateCar.ajax',
	    para: temp
    };
    app.requestSdkForNeedLogin({
      param: param,
      beforeSend: () => {
        //发送请求之前执行
        // wx.showToast({
        //     title: '请稍候',
        //     icon: 'loading',
        //     duration: 10000
        // });
      },
      success: data => {
        wx.showToast({
          title: '成功',
          icon: 'success',
          duration: 4000
        })
        var requestTimeFlagStr = "requestTimeFlag";
        var requestTimeFlag = sessionStorage.getItem(requestTimeFlagStr);
        if (!requestTimeFlag) {
          sessionStorage.setItem(requestTimeFlagStr, new Date().toString());
        }
        if (data.successFlag) {
          // this.setData({
          //   toast1Hidden: false
          // });
          var starTime = new Date(sessionStorage.getItem(requestTimeFlagStr))
          var endTime = new Date();

          if (changePhoneAutoSaving || ChangeSubscribeViolationAutoSaving || endTime - starTime < 1000) {
            sessionStorage.removeItem(requestTimeFlagStr);
          

            // setTimeout(() => {
            //   this.setData({
            //     toast1Hidden: true
            //   });
            // }, 250);
            return;
          }

          setTimeout(() => {
            wx.navigateBack({
              delta: 2
            })
          }, 1500);
        } else {
          this.setData({
            "errors[0]": data.errormsg,
            errorClass: ""
          });
          setTimeout(() => {
            this.setData({
              errors: [],
              errorClass: "hide",
            });
          }, 1500);
        }
      },
      complete: data => {
        changePhoneAutoSaving = false;
        ChangeSubscribeViolationAutoSaving = false;
        this.setData({
          inputIsDisabled: ChangeSubscribeViolationAutoSaving
        });
        setTimeout(()=>{
           wx.hideToast();
        },1000)
      }
    });
  },
  readyDelete: function () {
    //预备删除
    this.setData({
      modalHidden: false
    });
  },
  cancelDelete: function () {
    //取消删除
    this.setData({
      modalHidden: true
    });
  },
  furtherCarInfo: function () {
    // 添加资料入口
    wx.navigateTo({
      url: '../furtherInfor/furtherInfor?carId=' + this.data.carId
    })
  },
  confirmDelete: function () {
    let carId = this.data.carId;
    //确认删除
    this.setData({
      modalHidden: true
    });
    app.getUserInfo(function (userInfo) {

      var param = {
        api: 'Service.UcCar.CarService.DeleteCar',
	      url: '/wx/carViola/deleteCar.ajax',
	      para: {
          carId: carId
        }
      };
      app.requestSdkForNeedLogin({
        param: param,
        beforeSend: () => {
          //发送请求之前执行
          // wx.showToast({
          //   title: '请稍候',
          //   icon: 'loading',
          //   duration: 10000,
          //   mask: true
          // });
        },
        success: data => {
          if (data.successFlag) {
            // this.setData({
            //     toast1Hidden: false
            // });
            wx.showToast({
              title: '请稍候',
              icon: 'loading',
              duration: 2000
            });
            setTimeout(() => {
              wx.navigateBack({
                delta: 2
              })
            }, 1500);
          } else {
            toast.show(this, data.errormsg)
          }
        },
        complete: data => {
        }
      });

    });

  },
  onShareAppMessage: function () {
    return {
      title: '还在为违章处理排队烦恼吗？',
      desc: '邮证查办违章，免费查询，实时提醒，快速在线缴罚款，车主最贴心的车务管家！ ',
      path: 'pages/carInfo/list/list'
    }
  }
})